package com._21cn._front.cms.page.pc;

import com._21cn._front.GenerateHandler;
import com._21cn.cms.common.obj.ResponseObj;
import com._21cn.cms.template.entity.Template;
import com._21cn.cms.template.service.TemplateService;
import com._21cn.cms.template.utils.TemplateHelper;
import com._21cn.cms.template.utils.label.ToolsLabel;
import com._21cn.cms.template.utils.label.YellowPageLabel;
import com._21cn.cms.yellow.entity.YellowPage;
import com._21cn.framework.http.HttpRequestInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component("pcYellowPageContent")
public class PcYellowPageContent implements GenerateHandler {
    private static Pattern pattern = Pattern.compile("(/yellow/pc/(\\d+).shtml$)");

    private static Integer templateId = 24;
    private static String templateContent = "";

    @Autowired
    private TemplateService templateService;

    @Autowired
    private YellowPageLabel yellowPageLabel;

    @Autowired
    private ToolsLabel toolsLabel;

    public ResponseObj generate(HttpServletRequest request) { HttpRequestInfo reqInfo = new HttpRequestInfo(request);

        ResponseObj responseObj = new ResponseObj();
        try
        {
            Matcher regexpMatcher = pattern.matcher(request.getRequestURL());
            if (regexpMatcher.find()) {
                String idStr = regexpMatcher.group(2);
                YellowPage yellowPage = this.yellowPageLabel.getYellowPage(idStr);
                Map maps = new HashMap();
                maps.put("yellowPage", yellowPage);
                maps.put("toolsLabel", this.toolsLabel);

                Template template = templateService.getById(templateId);
                templateContent = template.getContent();

                String content = TemplateHelper.evaluateTemplate(templateContent, new Map[] { maps });

                responseObj.setErrorCode(Integer.valueOf(0));
                responseObj.setMessage(content);
            }
        }
        catch (Exception e) {
            responseObj.setErrorCode(Integer.valueOf(1));
            responseObj.setMessage("生成页面异常");
        }

        return responseObj;
    }
}